import React, { useState } from 'react';
import { Card, Table, Button, Input, Select, Tag, Modal, Form, DatePicker, InputNumber, message } from 'antd';
import { SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined, FilterOutlined, ReloadOutlined } from '@ant-design/icons';
import { useSelector } from 'react-redux';

const { Option } = Select;
const { RangePicker } = DatePicker;

const CouponManagement = () => {
  const [form] = Form.useForm();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [modalType, setModalType] = useState('create'); // 'create' or 'edit'
  const [selectedCoupon, setSelectedCoupon] = useState(null);
  const [searchText, setSearchText] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const { userInfo } = useSelector((state) => state.auth);

  // 模拟的优惠券数据
  const [coupons, setCoupons] = useState([
    {
      id: '1',
      name: '新年全场8折券',
      code: 'NEWYEAR20',
      discount: 20,
      minOrderAmount: 0,
      maxDiscount: 100,
      startDate: '2024-01-01',
      endDate: '2024-01-31',
      usageCount: 125,
      maxUsageCount: 500,
      status: 'active',
      applicableTo: 'all',
      createdBy: 'admin',
    },
    {
      id: '2',
      name: '新用户专享券',
      code: 'NEWUSER50',
      discount: 50,
      minOrderAmount: 100,
      maxDiscount: 50,
      startDate: '2024-01-01',
      endDate: '2024-02-28',
      usageCount: 89,
      maxUsageCount: 200,
      status: 'active',
      applicableTo: 'new_users',
      createdBy: 'admin',
    },
    {
      id: '3',
      name: '会员日优惠券',
      code: 'MEMBER30',
      discount: 30,
      minOrderAmount: 150,
      maxDiscount: 80,
      startDate: '2024-01-15',
      endDate: '2024-01-15',
      usageCount: 234,
      maxUsageCount: 300,
      status: 'expired',
      applicableTo: 'members',
      createdBy: 'admin',
    },
    {
      id: '4',
      name: '春节大促券',
      code: 'SPRING25',
      discount: 25,
      minOrderAmount: 200,
      maxDiscount: 150,
      startDate: '2024-02-01',
      endDate: '2024-02-15',
      usageCount: 0,
      maxUsageCount: 400,
      status: 'upcoming',
      applicableTo: 'all',
      createdBy: 'admin',
    },
  ]);

  // 表格列定义
  const columns = [
    {
      title: '优惠券名称',
      dataIndex: 'name',
      key: 'name',
      render: (text) => <a href="#">{text}</a>,
    },
    {
      title: '优惠码',
      dataIndex: 'code',
      key: 'code',
      render: (text) => (
        <Tag color="blue" style={{ margin: 0 }}>{text}</Tag>
      ),
    },
    {
      title: '折扣',
      dataIndex: 'discount',
      key: 'discount',
      render: (value) => `${value}%`,
    },
    {
      title: '最小订单金额',
      dataIndex: 'minOrderAmount',
      key: 'minOrderAmount',
      render: (value) => (value > 0 ? `¥${value}` : '无限制'),
    },
    {
      title: '有效期',
      key: 'period',
      render: (record) => `${record.startDate} - ${record.endDate}`,
    },
    {
      title: '使用情况',
      key: 'usage',
      render: (record) => `${record.usageCount}/${record.maxUsageCount}`,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => {
        let color = '';
        let text = '';
        switch (status) {
          case 'active':
            color = 'green';
            text = '活跃';
            break;
          case 'upcoming':
            color = 'orange';
            text = '即将开始';
            break;
          case 'expired':
            color = 'default';
            text = '已过期';
            break;
          default:
            color = 'default';
            text = '未知';
        }
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <>
          {record.status !== 'expired' && (
            <Button
              type="text"
              icon={<EditOutlined />}
              onClick={() => handleEdit(record)}
              style={{ marginRight: 8 }}
            >
              编辑
            </Button>
          )}
          <Button
            type="text"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </>
      ),
      width: 120,
    },
  ];

  // 过滤优惠券数据
  const filteredCoupons = coupons.filter((coupon) => {
    const matchesSearch = coupon.name.toLowerCase().includes(searchText.toLowerCase()) ||
                         coupon.code.toLowerCase().includes(searchText.toLowerCase());
    const matchesStatus = statusFilter === 'all' || coupon.status === statusFilter;
    return matchesSearch && matchesStatus;
  });

  // 打开创建模态框
  const showCreateModal = () => {
    form.resetFields();
    setModalType('create');
    setIsModalVisible(true);
  };

  // 打开编辑模态框
  const handleEdit = (coupon) => {
    setSelectedCoupon(coupon);
    setModalType('edit');
    form.setFieldsValue({
      ...coupon,
      dateRange: [
        new Date(coupon.startDate),
        new Date(coupon.endDate),
      ],
    });
    setIsModalVisible(true);
  };

  // 删除优惠券
  const handleDelete = (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个优惠券吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        setCoupons(coupons.filter((coupon) => coupon.id !== id));
        message.success('优惠券已删除');
      },
    });
  };

  // 提交表单
  const handleSubmit = (values) => {
    if (modalType === 'create') {
      // 创建新优惠券
      const newCoupon = {
        id: Date.now().toString(),
        ...values,
        startDate: values.dateRange[0].format('YYYY-MM-DD'),
        endDate: values.dateRange[1].format('YYYY-MM-DD'),
        usageCount: 0,
        status: 'active',
        createdBy: userInfo?.username,
      };
      setCoupons([newCoupon, ...coupons]);
      message.success('优惠券创建成功');
    } else {
      // 编辑优惠券
      const updatedCoupons = coupons.map((coupon) =>
        coupon.id === selectedCoupon.id
          ? {
              ...coupon,
              ...values,
              startDate: values.dateRange[0].format('YYYY-MM-DD'),
              endDate: values.dateRange[1].format('YYYY-MM-DD'),
            }
          : coupon
      );
      setCoupons(updatedCoupons);
      message.success('优惠券更新成功');
    }
    setIsModalVisible(false);
  };

  // 刷新数据
  const handleRefresh = () => {
    // 这里应该调用API刷新数据，这里简化处理
    message.success('数据已刷新');
  };

  return (
    <div>
      <div style={{ marginBottom: 24 }}>
        <h2>优惠券管理</h2>
        <p style={{ color: '#8c8c8c' }}>管理和创建系统中的优惠券</p>
      </div>

      <Card
        bordered={false}
        style={{ borderRadius: 8, marginBottom: 24 }}
      >
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
          <div style={{ display: 'flex', gap: 16 }}>
            <div style={{ width: 200 }}>
              <Input
                placeholder="搜索优惠券名称或代码"
                prefix={<SearchOutlined />}
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
                style={{ borderRadius: 4 }}
              />
            </div>
            <Select
              placeholder="选择状态"
              value={statusFilter}
              onChange={setStatusFilter}
              style={{ width: 120 }}
              prefix={<FilterOutlined />}
            >
              <Option value="all">全部</Option>
              <Option value="active">活跃</Option>
              <Option value="upcoming">即将开始</Option>
              <Option value="expired">已过期</Option>
            </Select>
            <Button
              icon={<ReloadOutlined />}
              onClick={handleRefresh}
            >
              刷新
            </Button>
          </div>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={showCreateModal}
          >
            创建优惠券
          </Button>
        </div>

        <Table
          columns={columns}
          dataSource={filteredCoupons}
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
          rowKey="id"
        />
      </Card>

      {/* 创建/编辑优惠券模态框 */}
      <Modal
        title={modalType === 'create' ? '创建优惠券' : '编辑优惠券'}
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          style={{ maxHeight: '60vh', overflowY: 'auto' }}
        >
          <Form.Item
            name="name"
            label="优惠券名称"
            rules={[{ required: true, message: '请输入优惠券名称' }]}
          >
            <Input placeholder="请输入优惠券名称" />
          </Form.Item>

          <Form.Item
            name="code"
            label="优惠码"
            rules={[{ required: true, message: '请输入优惠码' }]}
          >
            <Input placeholder="请输入优惠码" />
          </Form.Item>

          <Form.Item
            name="discount"
            label="折扣比例"
            rules={[{ required: true, message: '请输入折扣比例' }]}
          >
            <InputNumber
              min={1}
              max={99}
              style={{ width: '100%' }}
              addonAfter="%"
            />
          </Form.Item>

          <Form.Item
            name="minOrderAmount"
            label="最小订单金额"
            rules={[{ required: true, message: '请输入最小订单金额' }]}
          >
            <InputNumber
              min={0}
              style={{ width: '100%' }}
              addonBefore="¥"
            />
          </Form.Item>

          <Form.Item
            name="maxDiscount"
            label="最大优惠金额"
            rules={[{ required: true, message: '请输入最大优惠金额' }]}
          >
            <InputNumber
              min={0}
              style={{ width: '100%' }}
              addonBefore="¥"
            />
          </Form.Item>

          <Form.Item
            name="maxUsageCount"
            label="最大使用次数"
            rules={[{ required: true, message: '请输入最大使用次数' }]}
          >
            <InputNumber
              min={1}
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item
            name="dateRange"
            label="有效期"
            rules={[{ required: true, message: '请选择有效期' }]}
          >
            <RangePicker style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            name="applicableTo"
            label="适用对象"
            rules={[{ required: true, message: '请选择适用对象' }]}
          >
            <Select placeholder="请选择适用对象">
              <Option value="all">所有用户</Option>
              <Option value="new_users">新用户</Option>
              <Option value="members">会员用户</Option>
            </Select>
          </Form.Item>

          <Form.Item style={{ textAlign: 'right' }}>
            <Button style={{ marginRight: 8 }} onClick={() => setIsModalVisible(false)}>
              取消
            </Button>
            <Button type="primary" htmlType="submit">
              {modalType === 'create' ? '创建' : '保存'}
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default CouponManagement;